package cn.dgut.training.service.impl;

import cn.dgut.training.dto.RoleDTO;
import cn.dgut.training.entity.Role;
import cn.dgut.training.mapper.RoleMapper;
import cn.dgut.training.service.IRoleService;
import cn.dgut.training.vo.pageVO.PageVO;
import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
@Transactional
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

    @Resource
    private RoleMapper roleMapper;




    public Set<String> queryByIds(Integer[] roleIds) {
        Set<String> roles = new HashSet<String>();
        if(roleIds.length == 0){
            return roles;
        }
        List<Role> roleList = new ArrayList<>();
        for(Integer id:roleIds) {
            QueryWrapper queryWrapper =new QueryWrapper();
            queryWrapper.eq("id", id);
            Role role = roleMapper.selectOne(queryWrapper);
            roleList.add(role);
        }

        for(Role role : roleList){
            roles.add(role.getName());
        }

        return roles;

    }

    public PageVO querySelective(String name) {

        RoleDTO roleDTO=new RoleDTO();
        roleDTO.setName(name);
        //构造分页
        IPage page1 = new Page();
        BeanUtils.copyProperties(roleDTO, page1);
        //获取条件查询构造器
        QueryWrapper queryWrapper = roleDTO.getWrapper(roleDTO);

        List<Role> roles= roleMapper.selectList(queryWrapper);

        PageVO pageVO = new PageVO("default",roles);

        return pageVO;

    }

    public List<Role> queryAll() {

        QueryWrapper queryWrapper=new QueryWrapper();
        List<Role> roles=roleMapper.selectList(queryWrapper);
        return roles;
    }

    public boolean checkExist(String name) {
        QueryWrapper queryWrapper=new QueryWrapper();
        if(!StringUtils.isEmpty(name))
        queryWrapper.eq("name",name);

        List<Role> roles=roleMapper.selectList(queryWrapper);

        return roles.size()!=0;
    }

    public void add(Role role) {
        role.setAddTime(DateTime.now());
        role.setUpdateTime(DateTime.now());
        roleMapper.insert(role);
    }
}
